<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网络聊天室</title>
</head>
<style>
    #contains {
        background-color: pink;
        width: 1000px;
        height: 700px;
        margin: auto;
    }

    #username {
        background-color: skyblue;
        width: 1000px;
        height: 30px;
    }

    #left {
        background-color: silver;
        width: 700px;
        height: 640px;
        float: left;
        position: relative;
    }

    #content {
        background-color: silver;
        width: 700px;
        height: 400px;
        /*display: none;*/
        visibility: hidden;
    }

    #right {
        width: 300px;
        height: 640px;
        float: right;
    }

    #hyList {
        height: 270px;
        overflow-y: scroll;
        background: antiquewhite;
    }

    #xtList {
        height: 270px;
        overflow-y: scroll;
        background: antiquewhite;
    }

    #input {
        margin-bottom: 0px;
        position: absolute;
        bottom: 0px;
    }

    #mes_left {
        float: left;
        border: 2px aqua;
        max-width: 490px;
    }

    #mes_right {
        float: right;
        border: 2px aqua;
        max-width: 490px;
    }

    #hy {
        display: block;
        width: 300px;
    }

    textarea {
        resize: none;
        border: none;
        outline: none
    }
</style>
<body>
<div id="contains">
    <div id="username" style="height: 80px;">
<!--        <h3 style="text-align: center;padding-top: 20px">用户：张三<span>-在线</span></h3></br>-->
    </div>
    <div id="Inchat" style="text-align: center;color:blue; height: 20px; weight:100%;">

    </div>
    <div id="left">
        <div id="content">

        </div>
        <div id="input">
            <textarea type="text" id="input_text" style="width: 695px;height: 200px;" placeholder="请输入聊天内容"></textarea>
            <button id="submit" style="float: right; height: 30px">发送</button>
        </div>
    </div>
    <div id="right">
        <p id="hy" style="text-align: center;">好友列表</p>
        <div id="hyList">

        </div>
        <p id="xt" style="text-align: center">系统消息</p>
        <div id="xtList">

        </div>
    </div>
</div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
    var toName;
    var username;

    //点击好友名称展示相关消息
    function showChat(name) {
        toName = name;
        //现在聊天框
        $("#content").html("");
        $("#content").css("visibility", "visible");
        $("#Inchat").html("当前正与" + toName + "聊天");
        //从sessionStorage中获取历史信息
        var chatData = sessionStorage.getItem(toName);
        if (chatData != null) {
            $("#content").html(chatData);
        }
    }

    $(function () {
        $.ajax({
            url: "getUsername",
            success: function (res) {
                username = res.msg;

            },
            async: false //同步请求，只有上面好了才会接着下面
        });
        //建立websocket连接
        //获取host解决后端获取httpsession的空指针异常
        var host = window.location.host;
        var ws = new WebSocket("ws://" + host + "/chat");
        //建立连接
        ws.onopen = function (evt) {

            $("#username").html("<h3 style=\"text-align: center; height: 80px ;padding-top: 20px\">用户：" + username + "<span style='float: right;color: green'>在线</span></h3>");

        }

        //接收服务端消息触发事件
        ws.onmessage = function (evt) {
            //获取服务端推送的消息
            const dataStr = evt.data;
            //将dataStr转换为json对象
            const res = JSON.parse(dataStr);
            console.info("打印消息" + res.isSystem)

            //判断是否是系统消息
            if (res.isSystem) {
                //系统消息
                //1.好友列表展示
                //2.系统广播的展示
                //此处声明的变量是调试时命名的，可以直接合并
                const names = res.message;
                let userListStr = "";
                let broadcastListStr = "";
                const temp01 = "<a style=\"text-align: center; display: block;\" onclick='showChat(\"";
                const temp03 = "\")'>";
                const temp04 = "</a></br>";
                for (const name of names) {
                    if (name != username) {
                        // temp = "<a style='text-align: center; onclick=\"showChat("+name+")\"/></br>";
                        userListStr +=  temp01+name+temp03+name+temp04;
                        broadcastListStr += "<p style='text-align: center'>" + name + "上线了</p>";
                    }
                }
                console.log(userListStr)
                //渲染好友列表和系统广播
                $("#hyList").html(userListStr);
                $("#xtList").html(broadcastListStr);
            } else {
                //不是系统消息
                let str = "<span id='mes_left'>" + res.message + "</span></br>";
                if (toName === res.fromName) {
                    $("#content").append(str);
                }
                var chatData = sessionStorage.getItem(res.fromName);
                if (chatData != null) {
                    str = chatData + str;
                }
                //保存聊天消息
                sessionStorage.setItem(toName, str);
            }
            ;
        }
        ws.onclose = function () {
            $("#username").html("<h3 style=\"text-align: center; height: 80px ;padding-top: 20px\">用户：" + username + "<span>-离线</span></h3>");
        }

        //发送消息
        $("#submit").click(function () {
            //1.获取输入的内容
            const data = $("#input_text").val();
            //2.清空发送框
            $("#input_text").val("");
            const json = {"toName": toName, "message": data};
            //将数据展示在聊天区
            let str = "<span id='mes_right'>" + data + "</span></br>";
            $("#content").append(str);
            let chatData = sessionStorage.getItem(toName);
            if (chatData != null) {
                str=chatData + str;
            }
            sessionStorage.setItem(toName,str);
            //3.发送数据
            ws.send(JSON.stringify(json));
        })
    })
</script>
<script src="https://eqcn.ajz.miesnfu.com/wp-content/plugins/wp-3d-pony/live2dw/lib/L2Dwidget.min.js"></script>
<!--小帅哥： https://unpkg.com/live2d-widget-model-chitose@1.0.5/assets/chitose.model.json-->
<!--萌娘：https://unpkg.com/live2d-widget-model-shizuku@1.0.5/assets/shizuku.model.json-->
<!--小可爱（女）：https://unpkg.com/live2d-widget-model-koharu@1.0.5/assets/koharu.model.json-->
<!--小可爱（男）：https://unpkg.com/live2d-widget-model-haruto@1.0.5/assets/haruto.model.json-->
<!--初音：https://unpkg.com/live2d-widget-model-miku@1.0.5/assets/miku.model.json-->
<!-- 上边的不同链接显示的是不同的小人，这个可以根据需要来选择 下边的初始化部分，可以修改宽高来修改小人的大小，或者是鼠标移动到小人上的透明度，也可以修改小人在页面出现的位置。 -->
<script>
    /*https://unpkg.com/live2d-widget-model-shizuku@1.0.5/assets/shizuku.model.json*/
    L2Dwidget.init({
        "model": {
            jsonPath:
                "https://unpkg.com/live2d-widget-model-shizuku@1.0.5/assets/shizuku.model.json",
            "scale": 1
        }, "display": {
            "position": "right", "width": 110, "height": 150,
            "hOffset": 0, "vOffset": -20
        }, "mobile": {"show": true, "scale": 0.5},
        "react": {"opacityDefault": 0.8, "opacityOnHover": 0.1}
    });
</script>
</html>